/**********************************************************/
/* Goblin Defense - A tower defense game for Wii Homebrew */
/* Copyright (C) 2009 Ricardo Bueno Cordeiro              */
/* Licensed under de GNU General Public License v2.0      */
/*   See license_gplv2.txt for detalis                    */
/**********************************************************/

#include <gccore.h>
#include <wiiuse/wpad.h>

#include "toolbox.h"
#include "draw.h"

#include "weapons/thrower.h"
#include "weapons/hitter.h"

Toolbox::Toolbox() {
	this->gold = 50;
	this->shoes = 0;
	this->horns = 0;

	for (u32 i = 0; i < NUM_TOOLS; i++)
		this->tools[i] = NULL;
	
	this->selected_tool = 0;
	this->tools[0] = new ToolItem<WeaponThrower>(0);
	this->tools[1] = new ToolItem<WeaponHitter>(1);
}

void Toolbox::clear() {
	this->gold = 50;
	this->shoes = 0;
	this->horns = 0;
	this->selected_tool = 0;
}

int Toolbox::update(int state, u32 step, WPADData *wiimote_data) {
	return 0;
}

void Toolbox::draw(int state) {
	DR_configure(DRAW_CONF_DRAW_TEXTURE);
	for (u32 i = 0; i < NUM_TOOLS; i++)
		this->tools[i]->draw_tool();

	DR_configure(DRAW_CONF_DRAW_NO_TEXTURE);
	if (this->selected_tool >= 0)
		this->tools[this->selected_tool]->mark_selected(255, 255, 255, 100);
}

void Toolbox::text(int state) {
	DR_draw_text(256, 180, 30, "%d/%d/%d", this->gold, this->shoes, this->horns);
}

void Toolbox::select_weapon(f32 x, f32 y) {
	this->selected_tool = -1;
	
	for (u32 i = 0; i < NUM_TOOLS; i++) {
		if (this->tools[i]->inside(x, y)) {
			this->selected_tool = i;
			return;
		}
	}
}

int Toolbox::legal_position(Map *map, f32 x, f32 y) {
	if (!this->has_selected())
		return 0;
	
	const ToolWeapon *selected = this->tools[this->selected_tool];

	int on_path = map->on_path(x, y, WEAPON_UPGRADABLE_SIZE / 2.0);
	int type_path = selected->get_position_type() == WEAPON_POSITION_PATH;

	return (on_path && type_path) || ((!on_path) && (!type_path));
}

void Toolbox::draw_selected(f32 x, f32 y, int legal) {
	if (!this->has_selected())
		return;
	
//	const ToolWeapon *selected = this->tools[this->selected_tool];
}

int Toolbox::has_selected() {
	return this->selected_tool >= 0;
}

int Toolbox::can_buy() {
	if (this->selected_tool < 0)
		return 0;

	const ToolWeapon *selected = this->tools[this->selected_tool];
	return (selected->gold_price() <= this->gold) && (selected->shoe_price() <= this->shoes) && (selected->horn_price() <= this->horns);
}

UpgradableWeapon *Toolbox::buy_at(f32 x, f32 y) {
	if (this->selected_tool >= 0)
		return this->tools[this->selected_tool]->buy_at(x, y);
	return NULL;
}

void Toolbox::add_gold(u32 g) {
	this->gold += g;
}

void Toolbox::add_shoes(u32 s) {
	this->shoes += s;
}

void Toolbox::add_horns(u32 h) {
	this->horns += h;
}
